package net.sf.midollo.net;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.net.URL;

public class NetUtils {

	public static void copySocketOptions(Socket dst, Socket src) throws IOException {
		dst.setSoTimeout(src.getSoTimeout());
		dst.setKeepAlive(src.getKeepAlive());
		dst.setReceiveBufferSize(src.getReceiveBufferSize());
		dst.setSendBufferSize(src.getSendBufferSize());
		//dst.setTcpNoDelay(src.getTcpNoDelay());
		//dst.setTrafficClass(src.getTrafficClass());
		//dst.setOOBInline(src.getOOBInline());
		//dst.setReuseAddress(src.getReuseAddress());
		//int linger = src.getSoLinger();
		//dst.setSoLinger(linger >= 0, linger);
	}

	public static HttpURLConnection getHttpConnection(URL url, String method) throws IOException {
		HttpURLConnection connection = (HttpURLConnection)url.openConnection();
		// Basic options
		connection.setAllowUserInteraction(false);
		connection.setDefaultUseCaches(false);
		connection.setUseCaches(false);
		if ("POST".equals(method)) {
			connection.setDoOutput(true);
			connection.setDoInput(true);
		} else if ("PUT".equals(method)) {
			connection.setDoOutput(true);
			connection.setDoInput(true);
		} else {
			connection.setDoOutput(false);
			connection.setDoInput(true);
		}
		// HTTP options
		connection.setInstanceFollowRedirects(false);
		connection.setRequestMethod(method);
		return connection;
	}
}
